package Server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.HashMap;



public class ChatServer extends ServerSocket
{
	private int port;
	private ServerSocket ss;
	private boolean isRunning = true;
	private ClientService clientService;
	private HashMap<String,Socket> map = new HashMap<String,Socket>();
	private String userName;
	
	public ChatServer(int p) throws IOException
	{
		port = p;
		ss = new ServerSocket(port);
	}
	
	//@Override
	public void run()
	{
		System.out.println("Server starting...");
		Socket clientSock = null;
		while(isRunning)
		{
			try
			{
				clientSock = ss.accept();
				//clientSock.getInetAddress();
				//String ip =  new String();
				userName = clientSock.getInputStream().toString();
				map.put(userName,clientSock);
				//System.out.println(map.get(clientSock.getInetAddress()));
				clientService = new ClientService(clientSock);
				clientService.start();
			}
			catch(IOException e)
			{
				break;
			}
		}
	}
	
	public void send2Client(String msg)
	{
	//	InputStream in = 
		
		Socket soc = map.get(userName);
		synchronized(soc)
		{
			try
			{
				OutputStream out = map.get(userName).getOutputStream();
				//out.write(msg.getBytes());
				out.flush();
			}
			catch(IOException e)
			{
				e.printStackTrace();
			}
		}
	}
}

class ClientService extends Thread
{
	private Socket sock;
	
	public ClientService(Socket s)
	{
		sock = s;
	}
	
	public OutputStream getOutputStream() throws IOException
	{
		return sock.getOutputStream();
	}
	
	@Override
	public void run()
	{
		byte[] buf = new byte[256];
		String str;
		try
		{
			
			InputStream in = sock.getInputStream();
			OutputStream out = sock.getOutputStream();
			while(true)
			{
				while(in.read(buf) != -1)
				{
					str = new String(buf);
					//System.out.println(String.format("%s",str));
					out.write(buf);
					out.flush();
					
					if(str.trim().equals("exit"))
						return;
					while(buf != null)
						str = "";
				}
				
			}
		}
		catch(IOException e)
		{
			
		}
	}
}